import {navigateBack, navigateTo, redirectTo, reLaunch, switchTab} from "@tarojs/taro";
import {toSearchByJson} from "../utils";

class Nav {
    /**
     * 返回
     * @param successCallback           成功回调
     */
    back(successCallback?: () => void) {
        navigateBack({
            success: () => {
                if (typeof successCallback === "function") successCallback();
            }
        }).then()
    }

    /**
     * 跳转页面
     * @param url                       链接
     * @param params                    参数
     * @param successCallback           成功回调
     */
    go(url: string, params?: object, successCallback?: () => void) {
        navigateTo({
            url: `/${url}${params ? `?${toSearchByJson(params)}` : ''}`,
            success: () => {
                if (typeof successCallback === "function") successCallback();
            }
        }).then()
    }

    /**
     * 关闭当前页面，跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。
     * @param url                       链接
     * @param params                    参数
     * @param successCallback           成功回调
     */
    redirectGo(url: string, params?: object, successCallback?: () => void) {
        redirectTo({
            url: `/${url}${params ? `?${toSearchByJson(params)}` : ''}`,
            success: () => {
                if (typeof successCallback === "function") successCallback();
            }
        }).then()
    }

    /**
     * 关闭所有页面，打开到应用内的某个页面
     * @param url                       链接
     * @param params                    参数
     * @param successCallback           成功回调
     */
    reLaunchGo(url: string, params?: object, successCallback?: () => void) {
        reLaunch({
            url: `/${url}${params ? `?${toSearchByJson(params)}` : ''}`,
            success: () => {
                if (typeof successCallback === "function") successCallback();
            }
        }).then()
    }

    /**
     * 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
     * @param url                       链接
     * @param params                    参数
     * @param successCallback           成功回调
     */
    switchToTab(url: string, params?: object, successCallback?: () => void) {
        switchTab({
            url: `/${url}${params ? `?${toSearchByJson(params)}` : ''}`,
            success: () => {
                if (typeof successCallback === "function") successCallback();
            }
        }).then()
    }
}


export default new Nav()
